/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable no-use-before-define */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable import/no-extraneous-dependencies */
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Spin } from 'antd';
import router from 'umi/router';
import styles from './index.less';

/**
 * @param {string} type news|adv，区分是广告还是新闻
 * @param {string} width 宽
 * @param {string} height 高
 * @param {string} position left|center|right 位置
 * @param {string} detailPath 新闻详情页路由
 * @param {string} direction 轮播图滚动方向（horizontal，vertical)
 * @param {string} platform 广告平台（citysite | tong_di）
 */
const Advertisement = ({
  type,
  width,
  height,
  position,
  detailPath,
  style,
  advType = 1,
  direction = 'vertical',
  platform: paramPlatform = 'citysite',
}) => {
  const [loading, setLoading] = useState(true);
  const [platform, setPlatform] = useState(paramPlatform);
  const [show, setShow] = useState(true);
  const iframeRef = useRef();

  useEffect(
    () => {
      const { hostname } = window.location;
      const showDomain = ['kuaidihelp.com', 'tongdiyiyou.com'];
      if (showDomain.some(val => hostname.match(val))) {
        // 降域解决iframe跨域问题
        showDomain.forEach(val => {
          if (hostname.match(val)) {
            document.domain = val;
          }
        });
        if (type == 'news') {
          setPlatform(`${paramPlatform}_news`);
          window.jumpTo = index => {
            router.push(`${detailPath}?index=${index}`);
          };
        }
      } else {
        setShow(false);
      }
    },
    [type, paramPlatform],
  );

  const onload = useCallback(
    () => {
      try {
        if (iframeRef.current.height == 0) {
          iframeRef.current.height = 0;
        }
        setLoading(false);
      } catch (error) {
        setShow(false);
        console.warn(error);
      }
    },
    [type],
  );

  useEffect(() => {
    const getMessage = e => {
      const { origin, data = {} } = e || {};
      if (origin == 'https://m.kuaidihelp.com' && type == 'adv' && data.height == 0) {
        setShow(false);
      }
    };
    window.addEventListener('message', getMessage);
    return () => {
      window.removeEventListener('message', getMessage);
    };
  }, []);

  return (
    <>
      {show && (
        <div className={styles[position]} style={style}>
          <Spin spinning={loading}>
            <iframe
              title="adv"
              height={height}
              ref={iframeRef}
              width={width}
              onLoad={onload}
              src={`//m.kuaidihelp.com/adv_news/advandnews?type=${type}&platform=${platform}&position=${advType}&width=${width}&height=${height}&detailPath=${detailPath}&direction=${direction}`}
              scrolling="no"
            />
          </Spin>
        </div>
      )}
    </>
  );
};
export default Advertisement;
